package com.whcoding.rabbitmq;

import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-09-30 15:30
 **/
public class ConnectionUtil {

	private static final Logger logger = LoggerFactory.getLogger(ConnectionUtil.class);

	/**
	 * 连接MQ
	 *
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() {
		//创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		Connection connection = null;
		//配置参数
		connectionFactory.setHost("127.0.0.1");//主机IP地址
		connectionFactory.setPort(5672);//端口
		connectionFactory.setVirtualHost("/");//虚拟机，默认/
		connectionFactory.setUsername("guest");//用户名
		connectionFactory.setPassword("guest");//密码

		//通过工厂创建连接
		try {
			connection = connectionFactory.newConnection();
		} catch (IOException ex) {
			logger.info("获取mq连接发生异常{}", ex.getMessage());
		} catch (TimeoutException tex) {
			logger.info("获取mq连接发生异常{}", tex.getMessage());
		}
		return connection;
	}

}
